/*
 * EventQueue.cpp
 *
 *  Created on: 2014年5月28日
 *      Author: ellzu
 */

#include <common/EventRunLoop/EventQueue.h>
#include "common/KGLog.h"

namespace EventRunLoop {

EventQueue::EventQueue(bool obstruct)
{
	pthread_mutex_init(&_mutex,0);
	pthread_cond_init(&_cond,0);
	_obstruct = obstruct;
}
EventQueue::~EventQueue()
{
	pthread_mutex_destroy(&_mutex);
	pthread_cond_destroy(&_cond);
}

void EventQueue::poseEvent(Event *e)
{
	if(e==0){
		return;
	}
	pthread_mutex_lock(&_mutex);
	_events.push_back(e);

	if(e->_isAsync==false){
        pthread_mutex_lock(&(e->_mutex));
        
        
        if(_obstruct){
            pthread_cond_signal(&_cond);
        }
		pthread_mutex_unlock(&_mutex);

		pthread_cond_wait(&(e->_cond),&(e->_mutex) );
		pthread_mutex_unlock( &(e->_mutex) );
		delete e;
	}else{
        if(_obstruct){
            pthread_cond_signal(&_cond);
        }
		pthread_mutex_unlock(&_mutex);
	}
}
void EventQueue::endEvent(Event *e)
{
	if(e->_isAsync==false){
		pthread_mutex_lock(&(e->_mutex));
//		pthread_cond_broadcast(&(e->_cond));
		pthread_cond_signal(&(e->_cond));
		pthread_mutex_unlock( &(e->_mutex) );
	}else{
		delete e;
	}
}
Event* EventQueue::takeEvent()
{
	Event *e = 0;
	pthread_mutex_lock(&_mutex);
	std::vector<Event*>::iterator iter = _events.begin();
	if(_obstruct){
		while(iter==_events.end()){
			pthread_cond_wait(&_cond,&_mutex);
			iter = _events.begin();
		}
	}
	if(iter!=_events.end()){
		e = *iter;
		_events.erase(iter);
	}
	pthread_mutex_unlock(&_mutex);

	return e;
}

Event* EventQueue::nextEvent()
{
	Event *e = 0;
	pthread_mutex_lock(&_mutex);
	std::vector<Event*>::iterator iter = _events.begin();

	if (iter != _events.end()) {
		e = *iter;
	}
	pthread_mutex_unlock(&_mutex);
	return e;
}

} /* namespace EventRunLoop */
